package com.example.contentprovider;

import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import android.widget.Button;


import com.tbruyelle.rxpermissions3.RxPermissions;

import java.util.ArrayList;

import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends AppCompatActivity {
    
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViewTable();
        new RxPermissions(this)
                .request(Manifest.permission.READ_SMS,
                        Manifest.permission.READ_CONTACTS,
                        Manifest.permission.WRITE_CONTACTS)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Throwable {
                        if ( aBoolean ) {
                            initViewSms();
                            initViewPhone();
                            initViewEmail();
                            initParse();
                        } else {
                        }
                    }
                });
    }
    public void initViewSms() {
        Button button = findViewById(R.id.btn_sms);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentResolver resolver = getContentResolver();
                Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI,
                        new String[]{
                                Telephony.Sms.ADDRESS,
                                Telephony.Sms.DATE,
                                Telephony.Sms.TYPE,
                                Telephony.Sms.BODY},
                        null, null, null);
                if ( cursor.getCount() > 0 ) {
                    cursor.moveToFirst();
                    //
                    do {
                        String address = cursor.getString(cursor.getColumnIndex("ADDRESS"));
                        String date = cursor.getString(cursor.getColumnIndex("DATE"));
                        String type = cursor.getString(cursor.getColumnIndex("TYPE"));
                        String body = cursor.getString(cursor.getColumnIndex("BODY"));
                        Log.e(TAG, "address:" + address + " date:" + date + " type:" + type + " body" + body);
                    } while (cursor.moveToNext());
                }
                cursor.close();
            }
        });
    }
    private void initParse(){
        String number = "111112221111";
        Uri uri = Uri.parse(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI+"/"+number);
        ContentResolver resolver = getContentResolver();
        Cursor cursor  = resolver.query(uri,
                new String[]{
                        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}
                        ,null,null,null);
        if ( cursor.getCount() > 0 ) {
            cursor.moveToFirst();
            do {
                String cName = cursor.getString(0);

                Log.e(TAG, "姓名:" + cName + " 手机号:" + number);
            } while (cursor.moveToNext());
        }else {
            Log.e(TAG, "你查的人怕不是一个骨灰盒");
        }
        cursor.close();
    }
    private void initViewPhone() {
        Button button = findViewById(R.id.btn_phone);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentResolver resolver = getContentResolver();
                Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
                Cursor cursor = resolver.query(uri,
                        null, null, null, null);
                if ( cursor.getCount() > 0 ) {
                    cursor.moveToFirst();
                    do {
                        String cName = cursor.getString(cursor.getColumnIndex
                                (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String cPhone = cursor.getString(cursor.getColumnIndex
                                (ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.e(TAG, "姓名:" + cName + " 手机号:" + cPhone);
                    } while (cursor.moveToNext());
                }
                cursor.close();
            }
        });
    }
    private void initViewEmail() {
        Button button = findViewById(R.id.btn_in);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //创建无关联账户：IMTI
                ContentProviderOperation op1 =
                        ContentProviderOperation.newInsert
                                (ContactsContract.RawContacts.CONTENT_URI)
                                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "IMTI")
                                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.example.contentprovider")
                                .withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
                                    ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
                                .build();

                //创建该账户的联系人用户名：尼玛
                ContentProviderOperation op2 =
                        ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, 0)
                                .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "妈呀")
                                .build();
                //创建联系人的手机号码
                ContentProviderOperation op3 =
                        ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, 0)
                                .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
                                    ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "13888889999")
                                .withValue(ContactsContract.Data.IS_PRIMARY, "1")
                                .build();
                //创建联系人的邮箱账号
                ContentProviderOperation op4 =
                        ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                                .withValueBackReference(ContactsContract.CommonDataKinds.Email.RAW_CONTACT_ID, 0)
                                .withValue(ContactsContract.Data.MIMETYPE,
                                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                                .withValue(ContactsContract.CommonDataKinds.Email.DATA, "1234567@qq.com")
                                .withValue(ContactsContract.CommonDataKinds.Email.TYPE,
                                    ContactsContract.CommonDataKinds.Email.TYPE_MOBILE)
                                .build();
                ArrayList<ContentProviderOperation> operations = new ArrayList<>();
                operations.add(op1);
                operations.add(op2);
                operations.add(op3);
                operations.add(op4);
                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, operations);
                } catch (OperationApplicationException e) {
                    e.printStackTrace();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void initViewTable() {

        //访问Contentprovider类似于访问网站
        //浏览器（contentresolver),网址（uri）

        /*for (int i = 0; i < 5; i++) {

            ContentValues cv = new ContentValues();

            cv.put(StudentModel.NAME, "张三" + i);
            cv.put(StudentModel.COMPANY, "基因研究所" + i);
            cv.put(StudentModel.JOB, "研究基因重组" + i);

            getContentResolver().insert(MyContentProvider.INSERT_DATA, cv);

        }*/


        Cursor cursor = getContentResolver().query(
                MyContentProvider.QUERY_ALL, null,
                null, null, null);

        if ( cursor.getCount() > 0 ) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndexOrThrow(StudentModel.NAME));

                String company = cursor.getString(cursor.getColumnIndexOrThrow(StudentModel.COMPANY));

                String job = cursor.getString(cursor.getColumnIndexOrThrow(StudentModel.JOB));

                Log.e(TAG, "姓名：" + name + " 单位：" + company + " 工作：" + job);

            } while (cursor.moveToNext());

            cursor.close();
        }
    }
}